package com.zhl.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {

    @Value("${spring.application.name}")
    private String appName;
    //负载均衡客户端对象(基于此对象可以从nacos中获取服务列表,
    // 并且可以基于一定的算法从列表中获取一个服务实例)

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer/doRestEchol1")
    public String doRestEchol01() {
        //serviceId要在nacos的服务列表中
        ServiceInstance choose = loadBalancerClient.choose("rest-provider");
        String ip = choose.getHost();
        int port = choose.getPort();
        String url = String.format("http://%s:%s/provider/echo/%s", ip, port, appName);
        return restTemplate.getForObject(url, String.class);//使用了负载均衡
    }

    @Autowired//此注解优先按属性类型进行对象的查找,如果相同类型存在多个,则按照属性名与方法名对应查找
    @Qualifier("loadBalanceRestTemplate")//可以使用此注解指定要注入的具体对象
    private RestTemplate loadBalanceRT;

    @GetMapping("/consumer/doRestEchol2")
    public String doRestEchol02() {
        String url = String.format("http://rest-provider/provider/echo/%s", appName);
        return loadBalanceRT.getForObject(url, String.class);//使用了负载均衡
    }
}
